package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.SystemClock;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.util.Log;

import com.hjq.base.BaseDialog;
import com.hjq.http.lifecycle.ApplicationLifecycle;
import com.hjq.http.listener.HttpCallback;
import com.hjq.widget.layout.SettingBar;
import com.qiantu.api.db.HandleListener;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLDeviceActionDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.database.LocalDataBase;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.DeviceBindGroupBean;
import com.qiantu.api.entity.ProtocolSwitchResultBean;
import com.qiantu.api.entity.UniversalDeviceAction;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.bean.AddDeviceBean;
import com.qiantu.phone.manager.ActivityManager;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.ui.uiutil.CoorTools;
import com.qiantu.phone.utils.AddDeviceParseUtil;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.event.RefreshControllerEvent;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.ui.dialog.BottomProtocolSwitchDialog;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;

import java.io.Console;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class  ControllerSettingActivity extends AppActivity {
    private SettingBar itemSmartControllerName;
    private SettingBar itemSmartControllerId;
    private SettingBar itemBrand;
    private SettingBar itemIpAddress;
    private SettingBar itemMac;
    private View itemSmartPanelConfigLayout;
    private SettingBar itemSmartPanelConfig;
    private SettingBar itemSmartPanelInfo;
    private SettingBar itemFirmwareUpdate;
    private SettingBar itemFeedbackQuestions;
    private SettingBar itemModel;
    private View itemModelLayout;
    private SettingBar itemReplace;
    private SettingBar itemLoadDevice;
    private SettingBar itemDeviceCompose;
    private SettingBar itemwifiNetwork;
    private TextView btnStopStartUsing;
    private View itemStopStartUsing;
    private ControllerBean mControllerBean;
    private String controllerSerialNo;
    private String protocolSwitchQueryCode;
    private WifiManager wifiManager;
    private AddDeviceBean.DeviceConfigNetworkBean mDeviceConfigNetworkBean;
    long[] mHits = new long[3];// 数组长度表示要点击的次数，3表示3次点击，4表示4次点击。数组初始化都为0

    public static void start(Context context, String controllerSerialNo) {
        Intent intent = new Intent(context, ControllerSettingActivity.class);
        intent.putExtra("controllerSerialNo", controllerSerialNo);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_controller_setting;
    }

    @Override
    protected void initView() {
        controllerSerialNo = getString("controllerSerialNo");
        itemSmartControllerName = findViewById(R.id.item_smart_controller_name);
        itemSmartControllerId = findViewById(R.id.item_smart_controller_id);
        itemBrand = findViewById(R.id.item_brand);
        itemIpAddress = findViewById(R.id.item_ip_address);
        itemMac = findViewById(R.id.item_mac);
        itemSmartPanelConfigLayout = findViewById(R.id.item_panel_layout);
        itemSmartPanelConfig = findViewById(R.id.item_smart_panel_config);
        itemSmartPanelInfo = findViewById(R.id.item_bind_info);
        itemFirmwareUpdate = findViewById(R.id.item_firmware_update);
        itemFeedbackQuestions = findViewById(R.id.item_feedback_questions);
        itemModel = findViewById(R.id.item_model);
        itemModelLayout = findViewById(R.id.item_model_layout);
        itemReplace = findViewById(R.id.item_fix_replace);
        itemLoadDevice = findViewById(R.id.item_load_device);
        itemDeviceCompose = findViewById(R.id.item_device_compose);
        btnStopStartUsing = findViewById(R.id.btn_stop_start_using);
        itemStopStartUsing = findViewById(R.id.item_stop_start_using);
        itemwifiNetwork = findViewById(R.id.item_wifi_network_configuration);
        View btnDelete = findViewById(R.id.btn_delete);
        setOnClickListener(itemSmartControllerName, itemFirmwareUpdate, itemFeedbackQuestions,
                itemModel, itemReplace, itemLoadDevice, itemDeviceCompose, btnStopStartUsing, btnDelete, itemSmartPanelConfig,itemSmartPanelInfo,itemwifiNetwork);


        itemSmartControllerId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);//原数组，原数组拷贝起始点，目标数组，目标数组拷贝起始点。
                mHits[mHits.length - 1] = SystemClock.uptimeMillis();// 开机后开始计算的时间，每次放在最后一个，
                if ((mHits[mHits.length - 1] - mHits[0]) <= 500) {//最后一个和第一个相差500毫秒
                    if("0x1501".equals(mControllerBean.getProductModel()) || "0x1503".equals(mControllerBean.getProductModel())){
                        Intent intent = new Intent(getContext(), ControllerOtherSettingActivity.class);
                        intent.putExtra("controllerSerialNo",controllerSerialNo);
                        startActivity(intent);
                    }
                }
            }
        });
        itemSmartControllerId.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText("label",mControllerBean.getCodeNo());
                clipboardManager.setPrimaryClip(clipData);
                toast("复制成功");
                return false;
            }
        });
    }

    @Override
    protected void initData() {
        mControllerBean = LLControllerDBManager.getInstance(getContext()).getControllerBySerialNo(controllerSerialNo);
        updateView();
        getSetting();
    }

    private void getSetting(){
        LLHttpManager.getControllerSettings(this, controllerSerialNo, new HttpCallback<HttpData<ControllerBean>>(this){
            @Override
            public void onStart(Call call) {
                super.onStart(call);
            }

            @Override
            public void onSucceed(HttpData<ControllerBean> result) {
                super.onSucceed(result);
                ControllerBean newControllerBean = result.getData();
                mControllerBean.setName(newControllerBean.getName());
                mControllerBean.setCodeNo(newControllerBean.getCodeNo());
                mControllerBean.setIp(newControllerBean.getIp());
                mControllerBean.setDeviceMac(newControllerBean.getDeviceMac());
                mControllerBean.setProductInfoDto(newControllerBean.getProductInfoDto());
                mControllerBean.setProductInfoSerialNo(newControllerBean.getProductInfoSerialNo());
                mControllerBean.setIsDisable(newControllerBean.getIsDisable());
                mControllerBean.setImageUrl(newControllerBean.getImageUrl());
                mControllerBean.setVersion(newControllerBean.getVersion());
                mControllerBean.setProductModel(newControllerBean.getProductModel());
                mControllerBean.setProtocol(newControllerBean.getProtocol());
                mControllerBean.setBrandProtocols(newControllerBean.getBrandProtocols());
                mControllerBean.setSsid(newControllerBean.getSsid());
                updateView();
                LLControllerDBManager.getInstance(getContext()).put(mControllerBean);
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }

    private void updateView(){
        if(mControllerBean == null){
            return;
        }
        if ("0x0509".equals(mControllerBean.getProductModel())){//面板
            itemSmartPanelConfigLayout.setVisibility(View.VISIBLE);
            itemSmartPanelInfo.setVisibility(View.GONE);
            itemLoadDevice.setVisibility(View.GONE);
        }if ("0x1006".equals(mControllerBean.getProductModel())){//kgx
            itemSmartPanelConfigLayout.setVisibility(View.GONE);
            itemSmartPanelInfo.setVisibility(View.GONE);
            itemLoadDevice.setVisibility(View.GONE);
            itemFirmwareUpdate.setVisibility(View.VISIBLE);
        }else if("0x053D".equals(mControllerBean.getProductModel()) || "0x0554".equals(mControllerBean.getProductModel())){//温控屏面板
            itemSmartPanelConfigLayout.setVisibility(View.VISIBLE);
            itemFirmwareUpdate.setVisibility(View.VISIBLE);
            itemSmartPanelInfo.setVisibility(View.GONE);
        }else if("0x1005".equals(mControllerBean.getProductModel())){
            itemFirmwareUpdate.setVisibility(View.VISIBLE);
            itemSmartPanelConfigLayout.setVisibility(View.VISIBLE);
            itemLoadDevice.setVisibility(View.GONE);
        }else if("BR09".equals(mControllerBean.getProductModel())){

        }else if("0x1501".equals(mControllerBean.getProductModel())){
            itemFirmwareUpdate.setVisibility(View.VISIBLE);
            itemwifiNetwork.setVisibility(View.VISIBLE);
        }else if("DS-X".equals(mControllerBean.getProductModel())){//可视对讲
            itemIpAddress.setVisibility(View.GONE);
            itemMac.setVisibility(View.GONE);
        }else if("0x1503".equals(mControllerBean.getProductModel())){//可视对讲
            itemIpAddress.setVisibility(View.VISIBLE);
            itemMac.setVisibility(View.GONE);
            itemFirmwareUpdate.setVisibility(View.VISIBLE);
        }else if("0x0008".equals(mControllerBean.getProductModel())){//可视对讲
            itemIpAddress.setVisibility(View.GONE);
            itemMac.setVisibility(View.GONE);
            itemFirmwareUpdate.setVisibility(View.VISIBLE);
            itemDeviceCompose.setVisibility(View.VISIBLE);
        }else{
            itemFirmwareUpdate.setVisibility(View.VISIBLE);
        }

        //主机没有停启用
        if(mControllerBean.getIsSlave() && !mControllerBean.getProductModel().equals("0x1503")){
            updateStopStartButton(!mControllerBean.isIsDisable());
            itemIpAddress.setVisibility(View.GONE);
            itemMac.setVisibility(View.GONE);
        }else{
            itemStopStartUsing.setVisibility(View.GONE);
            itemIpAddress.setRightText(mControllerBean.getIp());
            itemMac.setRightText(mControllerBean.getDeviceMac());
        }
        itemSmartControllerName.setRightText(mControllerBean.getName());
        itemSmartControllerId.setRightText(mControllerBean.getCodeNo());
        if(mControllerBean.getProductInfoDto() != null && mControllerBean.getProductInfoDto().getManufactorInfo() != null){
            itemBrand.setRightText(mControllerBean.getProductInfoDto().getManufactorInfo().getAbbreviation());
        }
        itemFirmwareUpdate.setRightText("v" + mControllerBean.getVersion());
        if(mControllerBean.getBrandProtocols() != null && mControllerBean.getBrandProtocols().size() > 0){
            itemModelLayout.setVisibility(View.VISIBLE);
        }else{
            itemModelLayout.setVisibility(View.GONE);
        }
        if(mControllerBean.getProtocol() != null){
            itemModel.setRightText(mControllerBean.getProtocol().getBrandName() + " " + mControllerBean.getProtocol().getProtocolName());
        }
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (mControllerBean.getSsid()!=null){
            itemwifiNetwork.setRightText(mControllerBean.getSsid());
        }else{
            itemwifiNetwork.setRightText("有线");
        }
    }

    private void updateStopStartButton(boolean isDisable){
        if(isDisable){
            btnStopStartUsing.setText(R.string.stop_using);
            btnStopStartUsing.setTextColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor1));
//            btnStopStartUsing.setBackgroundResource(R.drawable.btn_transparent_8dp);
        }else{
            btnStopStartUsing.setText(R.string.start_using);
            btnStopStartUsing.setTextColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
//            btnStopStartUsing.setBackgroundResource(R.drawable.btn_theme_round_8dp);
        }
    }

    private void getDeviceByControllerSerialNo(){
        LLHttpManager.house_getdevices(new ApplicationLifecycle(), AppApplication.getInstance().getCurHouseInfo().getHouseSerialNo(), new HttpCallback<HttpData<List<DeviceBean>>>(this) {
            @Override
            public void onStart(Call call) {
            }
            @Override
            public void onSucceed(HttpData<List<DeviceBean>> result) {
                LLDeviceDBManager.getInstance(getContext()).refreshAllDevicesTx(result.getData(), new HandleListener() {
                    @Override
                    public void onCompleted() {
                        LLDeviceDBManager.getInstance(getContext()).putInTx(result.getData());
                        EventBus.getDefault().post(new RefreshControllerEvent());
                        EventBus.getDefault().post(new RefreshDeviceListEvent());
                        toast(R.string.switch_successful);
                        getSetting();
                        hideDialog();
                    }
                });
            }

            @Override
            public void onFail(Exception e) {
            }
        });
    }

    private void initDeviceTgpactionsList(String houseSerialNo) {
        LLHttpManager.getAllDeviceTgpactions(new ApplicationLifecycle(), houseSerialNo, new HttpCallback<HttpData<UniversalDeviceAction>>(this) {
            @Override
            public void onSucceed(HttpData<UniversalDeviceAction> result) {
                super.onSucceed(result);
                LLDeviceActionDBManager.getInstance(getContext()).refreshAllSoucecesTx(result.getData().getTgpActions(),null);
            }

            @Override
            public void onFail(Exception e) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.item_smart_controller_name:
                showBottomEditDialog(itemSmartControllerName.getRightText().toString());
                break;
            case R.id.item_firmware_update:
                FirmwareUpdateActivity.start(this, controllerSerialNo, 2);
                break;
            case R.id.item_feedback_questions:
//                int androidHeight = DensityUtils.getStatusBarHeight(this) + getResources().getDimensionPixelSize(R.dimen.dp_16);
//                StringBuilder stringBuilder = new StringBuilder(BuildConfig.SERVER_CENTER_URL + "pages/index/questions/questions");
//                stringBuilder.append("?token=").append("'" + AppApplication.getInstance().getLoginInfo().getToken() + "'")
//                        .append("&houseId=").append("'" + AppApplication.getInstance().getCurrentHouseSerialNo() + "'")
//                        .append("&serialNo=").append("'" + mControllerBean.getControllerSerialNo() + "'")
//                        .append("&androidHeight=").append("'" + androidHeight + "'");
//                BrowserActivity.start(getContext(), stringBuilder.toString());
                break;
            case R.id.item_model:
                showProtocolDialog();
                break;
            case R.id.item_load_device:
                LoadDeviceActivity.start(this, controllerSerialNo, LoadDeviceActivity.TYPE_CONTROLLER);
                break;
            case R.id.item_device_compose:
                DeviceComposeActivity.start(this,controllerSerialNo);
                break;
            case R.id.btn_stop_start_using:
//                if(mControllerBean == null){
//                    return;
//                }
//                boolean isDisable = mControllerBean.isIsDisable();
//                if(!isDisable){
//                    showStartStopHintDialog();
//                }else{
//                    controllerIsDisable();
//                }
                controllerIsDisable();
                break;
            case R.id.btn_delete:
                showDeleteHintDialog();
                break;
            case R.id.item_smart_panel_config:
                if(mControllerBean.getProtocol() != null && mControllerBean.getProtocol().getBrandValue() == 4504 && mControllerBean.getProtocol().getProtocolValue() == 2){
                    PanelKeyBindActivity.start(getContext(), controllerSerialNo);
                }else{
                    PanelBindConfigActivity.start(getContext(), controllerSerialNo);
                }
                break;
            case R.id.item_wifi_network_configuration:
                if(mControllerBean.getSsid()!=null){
                    gotoWifiView();
                }else{
                    showDialog_wifi();
                }

                break;
            case R.id.item_fix_replace:
                if(mControllerBean.getIsSlave()){
                    ControllerReplaceActivity.start(this, mControllerBean.getControllerSerialNo(),mControllerBean.getCodeNo(), mControllerBean.getName(),true,mControllerBean.getProductModel());
                }else{
                    ControllerReplaceWifiActivity.start(this, controllerSerialNo, mControllerBean.getCodeNo(), mControllerBean.getName(),mControllerBean.getProductModel());
                }
                break;
            case R.id.item_bind_info:
                KGPanelBindInfoActivity.start(this, mControllerBean.getControllerSerialNo());
                break;

        }
    }

    private BaseDialog mConfirmHintDialog;
    private ConfirmHintDialog.Builder mConfirmHintDialogBuilder_wifi;
    private void showDialog_wifi() {
        if(mConfirmHintDialog == null){
            mConfirmHintDialogBuilder_wifi = new ConfirmHintDialog.Builder(getContext());
            TextView tv_content = mConfirmHintDialogBuilder_wifi.findViewById(R.id.tv_content);
            tv_content.setGravity(Gravity.LEFT);
            tv_content.setPadding(39,0,0,0);
            //更换弹窗标题
            mConfirmHintDialogBuilder_wifi.setHint(getResources().getString(R.string.ok_wifi));
            mConfirmHintDialogBuilder_wifi.setLeftBtnText(getResources().getString(R.string.complete));
            mConfirmHintDialogBuilder_wifi.setRightBtnText(getResources().getString(R.string.change_lan));
            mConfirmHintDialogBuilder_wifi.setContent(getResources().getString(R.string.whether_need_wifi));
            mConfirmHintDialogBuilder_wifi.setListener(new ConfirmHintDialog.OnListener() {
                @Override
                public void onLeftClick(BaseDialog dialog) {
                    dialog.dismiss();
                }

                @Override
                public void onConfirm(BaseDialog dialog) {
                    dialog.dismiss();
                    gotoWifiView();
                }
            });
            mConfirmHintDialog = mConfirmHintDialogBuilder_wifi.create();
        }
        mConfirmHintDialog.show();
    }

    private void gotoWifiView(){
        Intent intent = new Intent(getContext(), AddDevice2Activity.class);
        //是否要重新配网的标识  1
        intent.putExtra("addDeviceName", "1");
        intent.putExtra("productLinkType", 2);
        //解析json文件
        List<AddDeviceBean> data = AddDeviceParseUtil.parseData(getContext());
        for (AddDeviceBean datum : data) {
            List<AddDeviceBean.DeviceConfigNetworkBean> distributionNetworkMethods = datum.getDistributionNetworkMethods();
            for (AddDeviceBean.DeviceConfigNetworkBean distributionNetworkMethod : distributionNetworkMethods) {
                if(distributionNetworkMethod.getProductInfo().getProductModel().equals(mControllerBean.getProductModel())){
                    mDeviceConfigNetworkBean = distributionNetworkMethod;
                    break;
                }
            }
        }
        intent.putExtra("links",mDeviceConfigNetworkBean.getLinks());
        startActivity(intent);
    }

    BottomEditDialog mBottomEditDialog;
    private void showBottomEditDialog(String text) {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(this);
            mBottomEditDialog.setLabel(getString(R.string.smart_controller_name));
            mBottomEditDialog.setHint(getString(R.string.please_enter_controller_name));
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    itemSmartControllerName.setRightText(mBottomEditDialog.getText());
                    updateControllerName(mBottomEditDialog.getText());
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        mBottomEditDialog.setText(text);
        mBottomEditDialog.setMaxLength(Constants.DEVICE_NAME_MAX_LENGTH);
        mBottomEditDialog.show();
    }

    private BaseDialog mConfirmCancelHintDialog;
    private ConfirmCancelHintDialog.Builder mConfirmCancelHintDialogBuilder;
    private void showStartStopHintDialog() {
        if (mConfirmCancelHintDialog == null) {
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(getActivity());
            mConfirmCancelHintDialogBuilder.setRightText(R.string.common_confirm);
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
        }
        mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
            @Override
            public void onLeftClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
            }

            @Override
            public void onRightClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
                controllerIsDisable();
            }
        });
        mConfirmCancelHintDialogBuilder.setContent(getString(R.string.stop_using_hint));
        mConfirmCancelHintDialog.show();
    }


    private void showDeleteHintDialog() {
        if (mConfirmCancelHintDialog == null) {
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(getActivity());
            mConfirmCancelHintDialogBuilder.setRightText(R.string.common_confirm);
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
        }
        mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
            @Override
            public void onLeftClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
            }

            @Override
            public void onRightClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
                deleteController();
            }
        });
        mConfirmCancelHintDialogBuilder.setContent(getString(R.string.delete_controller_hint));
        mConfirmCancelHintDialog.show();
    }

    private BottomProtocolSwitchDialog mBottomProtocolSwitchDialog;
    private void showProtocolDialog() {
        if (mBottomProtocolSwitchDialog == null) {
            mBottomProtocolSwitchDialog = new BottomProtocolSwitchDialog(this);
            mBottomProtocolSwitchDialog.setDialogClickListener(new BottomProtocolSwitchDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(int brand, int protocol) {
                    mBottomProtocolSwitchDialog.dismiss();
                    if(mControllerBean.getProtocol() != null &&  brand == mControllerBean.getProtocol().getBrandValue() && protocol == mControllerBean.getProtocol().getProtocolValue()){
                        protocolSwitch(brand, protocol);
                    }else{
                        showChangeTypeHintDialog(brand, protocol);
                    }

                }
                @Override
                public void onParameterClick(){
                    Intent intent = new Intent(getContext(), ControllerParameterActivity.class);
                    intent.putExtra("controllerSerialNo",mControllerBean.getControllerSerialNo());
                    getContext().startActivity(intent);
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomProtocolSwitchDialog);
        }
        mBottomProtocolSwitchDialog.setProtocols(mControllerBean.getBrandProtocols());
        mBottomProtocolSwitchDialog.setParameterShow(mControllerBean.getProductModel().equals("0x1004") || mControllerBean.getProductModel().equals("0x2002"));
        if(mControllerBean.getProtocol() != null){
            mBottomProtocolSwitchDialog.setSelected(mControllerBean.getProtocol().getBrandValue(), mControllerBean.getProtocol().getProtocolValue());
        }else {
            mBottomProtocolSwitchDialog.setDefaultSelect();//设置一个默认值
        }
        mBottomProtocolSwitchDialog.show();
    }

    private Runnable pollingRunnable = new Runnable(){
        @Override
        public void run() {
            queryProtocolSwitch();
        }
    };

    private void showChangeTypeHintDialog(int brand, int protocol) {
        if (mConfirmCancelHintDialog == null) {
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(getContext());
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
        }
        mConfirmCancelHintDialogBuilder.setHint(getContext().getString(R.string.device_protocol_switching_hint_title));
        mConfirmCancelHintDialogBuilder.setContent(getContext().getString(R.string.device_protocol_switching_hint));
        mConfirmCancelHintDialogBuilder.setRightText(R.string.ok);
        mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
            @Override
            public void onLeftClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
            }

            @Override
            public void onRightClick(BaseDialog dialog) {
                okTime = 10;
                mConfirmCancelHintDialogBuilder.dismiss();
                getHandler().postDelayed(timePollingRunnable, 1000);
                showChangeTypeSecondHintDialog(brand,protocol);
            }
        });
        mConfirmCancelHintDialog.show();
    }

    private void showChangeTypeSecondHintDialog(int brand, int protocol) {
        if (mConfirmCancelHintDialog == null) {
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(getContext());
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
        }
        mConfirmCancelHintDialogBuilder.setHint(getContext().getString(R.string.device_protocol_switching_hint_title));
        mConfirmCancelHintDialogBuilder.setContent("清空后，设备需要重新调试，确定继续吗？");
        mConfirmCancelHintDialogBuilder.setRightText("确定（"+ okTime+"）");
        mConfirmCancelHintDialogBuilder.setRightEnable(false);
        mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
            @Override
            public void onLeftClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
            }

            @Override
            public void onRightClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
                protocolSwitch(brand, protocol);
            }
        });
        mConfirmCancelHintDialog.show();
    }
    private int checkCount;

    private int okTime = 10;

    private Runnable timePollingRunnable = new Runnable(){
        @Override
        public void run() {
            okTime -- ;
            if(okTime <= 0){
                mConfirmCancelHintDialogBuilder.setRightEnable(true);
                mConfirmCancelHintDialogBuilder.setRightText("确定");
            }else{
                getHandler().postDelayed(timePollingRunnable, 1000);
                mConfirmCancelHintDialogBuilder.setRightText("确定（"+ okTime+"）");
            }
        }
    };

    private void protocolSwitch(int brand, int protocol){
        checkCount = 0;
        LLHttpManager.protocolSwitch(this, controllerSerialNo, brand, protocol, new HttpCallback<HttpData<ProtocolSwitchResultBean>>(this){
            @Override
            public void onStart(Call call) {
                showDialog(getString(R.string.switching));
            }

            @Override
            public void onSucceed(HttpData<ProtocolSwitchResultBean> result) {
                handleResult(result.getData());
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
                toast(R.string.switch_failed);
                hideDialog();
            }

            @Override
            public void onEnd(Call call) {
            }
        });
    }

    private void queryProtocolSwitch(){
        LLHttpManager.queryProtocolSwitch(this, protocolSwitchQueryCode, new HttpCallback<HttpData<ProtocolSwitchResultBean>>(this){
            @Override
            public void onStart(Call call) {
            }

            @Override
            public void onSucceed(HttpData<ProtocolSwitchResultBean> result) {
                handleResult(result.getData());
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
                toast(R.string.switch_failed);
                hideDialog();
            }

            @Override
            public void onEnd(Call call) {
            }
        });
    }

    private void handleResult(ProtocolSwitchResultBean data){
        protocolSwitchQueryCode = data.getQueryCode();
        //发起:0,等待执行:1,执行中:2,执行成功:3,执行失败:4,执行异常:5,未知:6
        if(data != null){
            switch (data.getActionStateType()){
                case 0:
                case 1:
                case 2:
                    checkCount++;
                    if(checkCount > 6){
                        toast(R.string.switch_failed);
                        hideDialog();
                    }else{
                        getHandler().postDelayed(pollingRunnable, 1000);
                    }
                    break;
                case 3:
                    initDeviceTgpactionsList(AppApplication.getInstance().getCurrentHouseSerialNo());
                    getSetting();
                    getDeviceByControllerSerialNo();
                    break;
                case 4:
                case 5:
                case 6:
                    toast(R.string.switch_failed);
                    hideDialog();
                    break;
            }
        }
    }

    private void updateControllerName(String name){
        LLHttpManager.updateControllerName(this, controllerSerialNo, name, new HttpCallback<HttpData<Void>>(this){
            @Override
            public void onStart(Call call) {
                showDialog(getString(R.string.modifying));
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                itemSmartControllerName.setRightText(name);
                LLControllerDBManager.getInstance(getContext()).updateName(controllerSerialNo, name);
                EventBus.getDefault().post(new RefreshControllerEvent());
                getSetting();
                if (CoorTools.isPanelModel(mControllerBean.getProductModel())){//面板类型
                    updateDeviceName(name);
                }else{
                    toast(R.string.reset_success);
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    //面板需要同时修改第一个设备名字
    private void updateDeviceName(String name){

        List<DeviceBean> deviceBeans = LLDeviceDBManager.getInstance(getContext()).getDeviceByControllerSerialNoAndBaseType(mControllerBean.getControllerSerialNo(),"wall_switch");
        if (!deviceBeans.isEmpty()){
            DeviceBean editDevice =  deviceBeans.get(0);
            editDevice.setName(name);
            LLHttpManager.modifyDevice(this, editDevice, new HttpCallback<HttpData<Void>>(this) {
                @Override
                public void onStart(Call call) {
                    showDialog(getString(R.string.setting));
                }

                @Override
                public void onSucceed(HttpData<Void> result) {
                    LLDeviceDBManager.getInstance(getContext()).put(editDevice);
                    toast(R.string.reset_success);
                }
                @Override
                public void onFail(Exception e) {
                    super.onFail(e);
                }

                @Override
                public void onEnd(Call call) {
                    hideDialog();
                }
            });
        }else {
            toast(R.string.reset_success);
        }
    }

    private void controllerIsDisable(){
        if(mControllerBean == null){
            return;
        }
        boolean isDisable = mControllerBean.isIsDisable();
        LLHttpManager.controllerIsDisable(this, controllerSerialNo, !isDisable, new HttpCallback<HttpData<Void>>(this){
            @Override
            public void onStart(Call call) {
                showDialog(getString(R.string.setting));
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                //设置成功，取反
                updateStopStartButton(isDisable);
                mControllerBean.setIsDisable(!isDisable);
                LLControllerDBManager.getInstance(getContext()).updateDisable(controllerSerialNo, !isDisable);
                EventBus.getDefault().post(new RefreshControllerEvent());
                Observable.create(new ObservableOnSubscribe<Boolean>() {
                    @Override
                    public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
                        boolean isUpdated = LLDeviceDBManager.getInstance(getContext()).updateDisableByControllerSerialNo(mControllerBean.getControllerSerialNo(), !isDisable);
                        emitter.onNext(isUpdated);
                    }
                }).subscribeOn(Schedulers.computation())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean isUpdated) throws Exception {
                                if (isUpdated) {
                                    EventBus.getDefault().post(new RefreshDeviceListEvent());
                                }
                                toast(R.string.set_success);
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {

                            }
                        });
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    private void deleteController(){
        LLHttpManager.controllerDelete(this, controllerSerialNo, new HttpCallback<HttpData<Void>>(this){
            @Override
            public void onStart(Call call) {
                showDialog(getString(R.string.deleting));
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                LLControllerDBManager.getInstance(getContext()).remove(controllerSerialNo);
                EventBus.getDefault().post(new RefreshControllerEvent());
                if(mControllerBean != null){
                    boolean isRemoved = LLDeviceDBManager.getInstance(getContext()).removeByControllerSerialNo(mControllerBean.getControllerSerialNo());
                    if(isRemoved){
                        EventBus.getDefault().post(new RefreshDeviceListEvent());
                    }
                }
                ActivityManager.getInstance().finishActivity(ControllerDeviceAcitvity.class);
                if(mControllerBean.getProductModel().equals("0x1503")){

                    ActivityManager.getInstance().finishActivity(LLRegionalGatewayActivity.class);
                }
                toast(R.string.delete_success);
                finish();
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }
}